using System;
using System.Text;
using System.IO;
using System.Security.Cryptography;
using System.Configuration;
using System.Collections;
using System.Data;
using ManticLabs.Data;


namespace ManticLabs.Common
{
	public sealed class Utility
	{
		
		private Utility(){}

		public static string PrefixInteger(char prefixChar, int pValue, int maxLength)
		{
			string sTemp;
			string sResult;

			sResult = "";
			sTemp = pValue.ToString();

			for (int i = maxLength; i>=sTemp.Length + 1; i--)
			{
				sResult = sResult + prefixChar;
			}
			sResult = sResult + sTemp;

			return sResult;
		}

        //public static string GenerateKey()
        //{
        //    try
        //    {
        //        DESCryptoServiceProvider des  = new DESCryptoServiceProvider();
        //        KeySizes[] ks = des.LegalKeySizes;

        //        string temp;

        //        des.GenerateIV();
        //        des.GenerateKey();

        //        temp = "";
        //        for (int i = 0; i < des.Key.Length; i++)
        //        {
        //            temp = temp + PrefixInteger('0', des.IV[i], 3);
        //        }
        //        temp = temp + "_";
        //        for (int i = 0; i < des.Key.Length; i++)
        //        {
        //            temp = temp + PrefixInteger('0', des.Key[i], 3);
        //        }

        //        return temp;
        //    }
        //    catch (Exception ex)
        //    {
        //        throw (new MLabsException("", "Source: Utility::GenerateKey: " + ex.Message, LogLevelType.ERROR));
        //    }
        //}


        //public static string Encrypt(string StringToEncrypt)
        //{

        //    try
        //    {
        //        DESCryptoServiceProvider des = new DESCryptoServiceProvider();
        //        string strSavedKey = ConfigurationSettings.AppSettings.Get("Key");
				
        //        string temp;

        //        string strIV = strSavedKey.Split('_')[0];
        //        string strKey = strSavedKey.Split('_')[1];

        //        byte[] IV = new byte[strIV.Length / 3];
        //        byte[] Key = new byte[strKey.Length / 3];

        //        for(int i = 0; i < strIV.Length / 3; i++)
        //        {
        //            IV[i] = byte.Parse(strIV.Substring(i * 3, 3));
        //        }

        //        for(int i = 0; i < strKey.Length / 3; i++)
        //        {
        //            Key[i] = byte.Parse(strKey.Substring(i * 3, 3));
        //        }

        //        //'create a memory stream and set its length to 0
        //        MemoryStream ms = new MemoryStream();
        //        ms.SetLength(0);

        //        //create a cryptostream based on the above memory stream
        //        CryptoStream encStream = new CryptoStream(ms, des.CreateEncryptor(Key, IV), CryptoStreamMode.Write);

        //        //convert the input string to bytes
        //        byte[] plainBytes = Encoding.Unicode.GetBytes(StringToEncrypt.ToCharArray());

        //        //encrypt & write the input string to stream
        //        encStream.Write(plainBytes, 0, plainBytes.GetLength(0));
        //        encStream.FlushFinalBlock();
        //        encStream.Close();

        //        //transform the encrypted data and return it
        //        temp = "";
				
        //        for(int i = 0; i < ms.ToArray().Length; i++)
        //        {
        //            temp = temp + PrefixInteger('0', int.Parse(ms.ToArray()[i].ToString()), 3);
        //        }

        //        return temp;
        //    }
        //    catch (Exception ex)
        //    {
        //        throw (new MLabsException("", "Source: Utility::GenerateKey: " + ex.Message, LogLevelType.ERROR));
        //    }
        //}		
		
        //public static string Decrypt(string StringToDecrypt)
        //{
        //    try
        //    {
        //        DESCryptoServiceProvider des = new DESCryptoServiceProvider();
        //        string strSavedKey = ConfigurationSettings.AppSettings.Get("Key");

        //        string strIV = strSavedKey.Split('_')[0];
        //        string strKey = strSavedKey.Split('_')[1];
        //        byte[] IV = new byte[strIV.Length / 3];
        //        byte[] Key = new byte[strKey.Length / 3];

        //        for(int i = 0; i < strIV.Length / 3; i++)
        //        {
        //            IV[i] = byte.Parse(strIV.Substring(i * 3, 3));
        //        }

        //        for(int i = 0; i < strKey.Length / 3; i++)
        //        {
        //            Key[i] = byte.Parse(strKey.Substring(i * 3, 3));
        //        }


        //        ///////////////////////////
        //        byte[] temp = new byte[StringToDecrypt.Length / 3];

        //        for(int i = 0; i < StringToDecrypt.Length / 3; i++)
        //        {
        //            temp[i] = byte.Parse(StringToDecrypt.Substring(i * 3, 3));
        //        }

        //        //initialize a memory stream from the input string 
        //        //        Dim ms As New MemoryStream(Encoding.Unicode.GetBytes(StringToDecrypt.ToCharArray()))
        //        MemoryStream ms  = new MemoryStream(temp);

        //        //create a cryptostream 
        //        CryptoStream decStream = new CryptoStream(ms, des.CreateDecryptor(Key, IV), CryptoStreamMode.Read);

        //        //allocate the buffer for reading 
        //        byte[] plainBytes = new byte[4096];
        //        decStream.Read(plainBytes, 0, (int )ms.Length);
        //        decStream.Close();

        //        //return the trimmed decrypted string
        //        char[] charA = {'0'};
        //        return Encoding.Unicode.GetString(plainBytes).TrimEnd(charA);
        //    }
        //    catch (Exception ex)
        //    {
        //        throw(new MLabsException("", "Source: Utility::Decrypt: " + ex.Message, LogLevelType.ERROR));
        //    }
        //}
		
		public static void AddToHashtable(Hashtable hash, object key, object valueObject)
		{
			AddToHashtable(hash, key, valueObject, true);
		}
		//it adds to hahstable if it key doesnt exist otherwise modify it
		public static void AddToHashtable(Hashtable hash, object key, object valueObject, bool caseSensitive)
		{
			if(hash != null && key != null)
			{
				if(caseSensitive)
				{
					if(hash.Contains(key))
						hash[key] = valueObject;
					else
						hash.Add(key, valueObject);
				}
				else
				{
					if(CaseIncensitiveContains(hash, key))
						hash[key] = valueObject;
					else
						hash.Add(key, valueObject);
				}
			}
		}

		public static bool	IsNull(object o)
		{
			if( o == null || (o is DBNull))
				return true;
			return false;
		}

		public static string MakeProperSQLParam(object o)
		{
			string str = "";
			if( o != null && !(o is System.DBNull))
			{
				str = Convert.ToString(o);
				for(int i = 0; i < str.Length; i++)
				{
					if((int)str[i] == 39)//single quote
					{
						string toReplace = "'" + str[i];
						str = str.Replace(new string(str[i], 1), toReplace);
						i++;
					}
				}
			}
			return str;
		}

		public static string MakeProperJavascriptString(object o)
		{
			string str = "";
            StringBuilder sb = new StringBuilder();

			if( o != null && !(o is System.DBNull))
			{
				str = Convert.ToString(o);

                for (int i = 0; i < str.Length; i++)
				{
                    if ((int)str[i] == 33 || (int)str[i] == 34 || (int)str[i] == 35 || (int)str[i] == 36 || (int)str[i] == 37 || (int)str[i] == 38 || (int)str[i] == 39 || (int)str[i] == 40 || (int)str[i] == 41 || (int)str[i] == 42 || (int)str[i] == 43 || (int)str[i] == 44 || (int)str[i] == 46 || (int)str[i] == 47 || (int)str[i] == 58 || (int)str[i] == 59 || (int)str[i] == 60 || (int)str[i] == 61 || (int)str[i] == 63 || (int)str[i] == 64 || (int)str[i] == 91 || (int)str[i] == 92 || (int)str[i] == 93 || (int)str[i] == 94 || (int)str[i] == 95 || (int)str[i] == 123 || (int)str[i] == 124 || (int)str[i] == 125) //escape !@#$%^&*()_+=[]{}\|;:",<.?/
                    {
                        sb.Append("\\" + str[i]);

                        // string toReplace = "\\" + sb[i];
                        //sb = sb.Replace(new string(sb[i], 1), toReplace);
                        //i += 1;
                    }
                    else
                        sb.Append(str[i]);

				}
				
			}
            return sb.ToString();
		}

       
		public static ArrayList SplitString(string val, string delim)
		{
			string[] fields = CustomSplit(val, delim);
			ArrayList tempFields = new ArrayList();
			for(int i=0; i<fields.Length; i++)
			{
				string field = fields[i];
				if(field != null && field.Trim().Length > 0)
					tempFields.Add(field);
			}
			return tempFields;
		}
        public static ArrayList SplitStringWithBlankValue(string val, string delim)
        {
            string[] fields = CustomSplit(val, delim);
            ArrayList tempFields = new ArrayList();
            for (int i = 0; i < fields.Length; i++)
            {
                string field = fields[i];
                tempFields.Add(field);
            }
            return tempFields;
        }

		public static ArrayList SplitStringAll(string val, string delim)
		{
			string[] fields = CustomSplit(val, delim);
			ArrayList tempFields = new ArrayList();
			for(int i=0; i<fields.Length; i++)
			{
				tempFields.Add(fields[i]);
			}
			return tempFields;
		}

		public static Hashtable ParseString(string query, string pairDelim, string valueDelim, bool caseSensitive)
		{
			Hashtable retVal = new Hashtable();
			if(
				query != null && query.Length > 0 && 
				pairDelim != null && pairDelim.Length > 0 &&
				valueDelim != null && valueDelim.Length > 0 
				)
			{
				int pairIndex = query.IndexOf(pairDelim);
				string rest = query;
				int valueIndex = -1;
				string key = "";
				string val = "";
				while(pairIndex != -1)
				{
					string keyVal = rest.Substring(0, pairIndex);
					rest = rest.Substring(pairIndex + pairDelim.Length);
					
					pairIndex = rest.IndexOf(pairDelim);

					valueIndex = keyVal.IndexOf(valueDelim);
					if(valueIndex == -1)//bad key pair
						continue;
					key = keyVal.Substring(0, valueIndex);
					val = keyVal.Substring(valueIndex + valueDelim.Length);
					AddToHashtable(retVal, key, val, caseSensitive);
				}
				valueIndex = rest.IndexOf(valueDelim);
				if(valueIndex != -1)
				{
					key = rest.Substring(0, valueIndex);
					val = rest.Substring(valueIndex + valueDelim.Length);
					AddToHashtable(retVal, key, val, caseSensitive);
				}
			}
			return retVal;
		}

		public static bool CaseIncensitiveContains(Hashtable table, object keyVal)
		{
			bool retVal = false;
			if(table != null)
			{
				IEnumerator keys = table.Keys.GetEnumerator();

				while(keys.MoveNext())
				{
					object key = keys.Current;
					if(key.ToString().ToLower() == keyVal.ToString().ToLower())
					{
						retVal = true;
						break;
					}
				}
			}
			return retVal;
		}

		public static string ReplaceString(string val, string from, string to)
		{
			string newValue = "";
			ArrayList tokens = SplitString(val, from);
			for(int i=0; i<tokens.Count; i++)
				newValue += Convert.ToString(tokens[i]) + to;
			return newValue;
		}

		public static string[] CustomSplit(string paramvals, string parseChar)
		{
			ArrayList retVal = new ArrayList();
			int eIndex = paramvals.IndexOf(parseChar);
			string temp = "";
			int sIndex = 0;
			if(eIndex != -1 )
			{
				while(eIndex != -1 && sIndex < paramvals.Length )
				{
					temp = paramvals.Substring(sIndex, eIndex - sIndex);
					retVal.Add(temp);
					sIndex = eIndex + parseChar.Length;
					eIndex = paramvals.IndexOf(parseChar,sIndex);
				}
			}
			//for last entry
			if( eIndex == -1 && sIndex < paramvals.Length)
			{
				temp = paramvals.Substring(sIndex);
				retVal.Add(temp);
			}
			string[] ret = new string[retVal.Count];

			for(int i = 0; i < retVal.Count; i++)
			{
				ret[i] = (string)retVal[i];
			}
			return ret;
		}

		public static string JavaScriptEscape(string str)
		{
			string retVal = "";
			if(str != null && str.Trim().Length > 0)
			{
				retVal = str.Replace("\\", "\\\\");
				retVal = retVal.Replace("\"", "\\\"");
				retVal = retVal.Replace("\'", "\\\'");
				retVal = retVal.Replace(Environment.NewLine, "\\n");

			}
			return retVal;
		}

		public static string UrlEncode(object val)
		{
            
			string strEncoded = Convert.ToString(val);
            strEncoded = Uri.EscapeUriString(strEncoded);
			//URLEncode is converting space into + expected value was %20
			strEncoded = strEncoded.Replace("+","%20");
			return strEncoded;
			
		}

		public static bool IsSameDate(DateTime date1, DateTime date2)
		{
			return (date1.Year == date2.Year && date1.Month == date2.Month && date1.Day == date2.Day);
		}

        public static string NullToEmpty(string s)
        {
            if (s == null)
                return "";
            else
                return s;
        }

	}	
}